//
//  SingleViewController.m
//  FitTime
//
//  Created by dllo on 16/3/31.
//  Copyright © 2016年 赵建平. All rights reserved.
//

#import "SingleViewController.h"
#import "V_SingleTableViewCell.h"
#import "SingleModel.h"
#import "MXPullDownMenu.h"
#import "Mp4SingleViewController.h"
#import "ASIHTTPRequest.h"
#import "ASINetworkQueue.h"
#import "Single.h"
#import "CoreDataManager.h"

@interface SingleViewController ()<UITableViewDataSource, UITableViewDelegate, MXPullDownMenuDelegate, dowmLoadButtonDelegate, ASIHTTPRequestDelegate>

@property (nonatomic, strong) NSMutableArray *singleModelArray;//装singleModel的数组

@property (nonatomic, copy) NSString *bodyWithTimeString;
@property (nonatomic, strong) NSArray *menuArray;
@property (nonatomic, strong) NSMutableArray *bodyArray;
@property (nonatomic, strong) SingleModel *singleModel;
@property (nonatomic, strong) NSArray *shaixuan;

@property (nonatomic, strong) NSMutableArray *datasource;

@property (nonatomic, strong) NSMutableArray *sendNextArray;//传给下一个控制器的数组
@property (nonatomic, strong)NSMutableArray *otherDataSource;
@property (nonatomic, assign) BOOL isHave;

// 下载
@property (nonatomic, retain) ASINetworkQueue *queue;
@property (nonatomic, strong) UIProgressView *progess;

@property (nonatomic, strong) NSString *Time; //当前事件选择;

@end

@implementation SingleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createTableView];
    [self getData];
    self.otherDataSource = [NSMutableArray arrayWithCapacity:0];
    self.isHave = YES;
    
    
//    [self initQue];
}

- (void)initQue
{
//    self.queue = [[ASINetworkQueue alloc] init];
//    [self.queue reset];
//    [self.queue setShowAccurateProgress:YES];
//    [self.queue go];
//    // 创建存放路径
//    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//    //初始化临时文件路径
//    NSString *folderPath = [path stringByAppendingPathComponent:@"temp"];
//    //创建文件管理器
//    NSFileManager *fileManager = [NSFileManager defaultManager];
//    //判断temp文件夹是否存在
//    BOOL fileExists = [fileManager fileExistsAtPath:folderPath];
//    
//    if (!fileExists) {
//        [fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
//    }
}

- (void)send:(NSString *)string WithNumber:(NSInteger)number
{
    NSLog(@"网址：：：：%@", string);
    self.queue = [[ASINetworkQueue alloc] init];
    [self.queue reset];
    [self.queue setShowAccurateProgress:YES];
    [self.queue go];
    // 创建存放路径
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents"];
    //初始化临时文件路径
    NSString *folderPath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"temp/%@", string]];
    //创建文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断temp文件夹是否存在
    BOOL fileExists = [fileManager fileExistsAtPath:folderPath];
    
    if (!fileExists) {
        [fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    //初始下载路径
    NSURL *url = [NSURL URLWithString:string];
    //设置下载路径
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    //设置ASIHTTPRequest代理
    request.delegate = self;
    //初始化保存ZIP文件路径
    NSString *savePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"/book_%ld.mp4", number]];
    //初始化临时文件路径
    NSString *tempPath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"temp/book_%ld.mp4.temp", number]];
    //设置文件保存路径
    [request setDownloadDestinationPath:savePath];
    //设置临时文件路径
    [request setTemporaryFileDownloadPath:tempPath];
    //设置进度条的代理
//    [request setDownloadProgressDelegate:<#(id)#>]
    //设置是是否支持断点下载
//    [request setAllowResumeForFileDownloads:YES];
    //设置基本信息
//    [request setUserInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInteger:number], nil]];
    
    NSLog(@"UserInfo=%@",request.userInfo);
    //添加到ASINetworkQueue队列去下载
    [self.queue addOperation:request];
    
}

//- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders
//{
//    NSLog(@"didReceiveResponseHeaders-%@",[responseHeaders valueForKey:@"Content-Length"]);
//    
//    NSLog(@"contentlength=%f",request.contentLength/1024.0/1024.0);
//    int bookid = [[request.userInfo objectForKey:@"bookID"] intValue];
//    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//    float tempConLen = [[userDefaults objectForKey:[NSString stringWithFormat:@"book_%d_contentLength",bookid]] floatValue];
//    NSLog(@"tempConLen=%f",tempConLen);
//    //如果没有保存,则持久化他的内容大小
//    if (tempConLen == 0 ) {//如果没有保存,则持久化他的内容大小
//        [userDefaults setObject:[NSNumber numberWithFloat:request.contentLength/1024.0/1024.0] forKey:[NSString stringWithFormat:@"book_%d_contentLength",bookid]];
//    }
//    
//}
//ASIHTTPRequestDelegate,下载完成时,执行的方法
//- (void)requestFinished:(ASIHTTPRequest *)request {
//    
//    int bookid = [[request.userInfo objectForKey:@"bookID"] intValue];
//    CustomCell *cell = (CustomCell *)[self.myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:bookid inSection:0]];
//    cell.downloadCompleteStatus = YES;
//    cell.progressView.progress = 0.0;
//}


#pragma mark - 创建tableView
- (void)createTableView {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, SCREENWIDTH, SCREENHEIGHT)];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 113, 0);

    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.tableView registerClass:[V_SingleTableViewCell class] forCellReuseIdentifier:@"V_SingleTableViewCellIdentifier"];
    
    [self.view addSubview:self.tableView];
    [self createPullMenu];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  
    
    return self.datasource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    V_SingleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"V_SingleTableViewCellIdentifier"];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    SingleModel *singleModel = self.datasource[indexPath.row];
    cell.singleModel = singleModel;
    
    cell.number = indexPath.row;
    cell.delegate = self;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return SCREENHEIGHT / 5;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    Mp4SingleViewController *mp4 = [[Mp4SingleViewController alloc] init];
    SingleModel *singleModel = self.datasource[indexPath.row];
    mp4.urlString = singleModel.url;
    mp4.time = singleModel.time;
    
    [self.navigationController pushViewController:mp4 animated:YES];
}

#pragma mark - 创建下拉菜单
- (void)createPullMenu {
    
    self.menuArray = @[@[@"全部部位", @"全身", @"胸部", @"背部", @"肩部", @"手臂", @"腹部", @"腿部", @"臀部"],@[@"全部时间",@"5分钟", @"10分钟", @"15分钟", @"20分钟", @"20分钟以上"]];
    MXPullDownMenu *mxPull = [[MXPullDownMenu alloc] initWithArray:self.menuArray selectedColor:[UIColor yellowColor]];
    mxPull.delegate = self;
    mxPull.frame = CGRectMake(0, 0, SCREENWIDTH, 30);
    [self.view addSubview:mxPull];
    
}

- (void)PullDownMenu:(MXPullDownMenu *)pullDownMenu didSelectRowAtColumn:(NSInteger)column row:(NSInteger)row {
    
    self.datasource = [NSMutableArray arrayWithCapacity:0];
    self.bodyWithTimeString = self.menuArray[column][row];
    
    //初始为全部部位数组
    if (self.otherDataSource.count == 0) {
        
        self.datasource = [NSMutableArray arrayWithArray:self.singleModelArray];
        
        self.otherDataSource = [NSMutableArray arrayWithArray:_datasource];
        
    }
    //******************************************
    if (column == 0) {
        if ([self.bodyWithTimeString isEqualToString:@"全部部位"]) {
            self.datasource = [NSMutableArray arrayWithArray:self.singleModelArray];
            
        } else {
            for (SingleModel *model in self.singleModelArray) {
                if ([model.part isEqualToString:self.bodyWithTimeString]) {
                    [self.datasource addObject:model];
                }
            }
        }
        
        self.otherDataSource = [NSMutableArray arrayWithArray:_datasource];
        
        // 对时间进行筛选
        if ([self.Time isEqualToString:@"全部时间"]){
            
            [self.datasource removeAllObjects];
            
            self.datasource = [NSMutableArray arrayWithArray:self.singleModelArray];
           
        } else if ([self.Time isEqualToString:@"20分钟以上"]){
            
            NSMutableString *string = [NSMutableString stringWithFormat:@"%@", self.Time];
            
            [self.datasource removeAllObjects];
            
            for (SingleModel *model in self.otherDataSource) {
                if (model.time >= string.intValue * 60) {
                    [self.datasource addObject:model];
                }
                
            }
            
        } else if (self.Time != nil){
            
            NSMutableString *string = [NSMutableString stringWithFormat:@"%@", self.Time];
            
            [self.datasource removeAllObjects];
            
            for (SingleModel *model in self.otherDataSource) {
                
                if (model.time >= (string.intValue - 5) * 60 && model.time <= (string.intValue + 1) * 60) {
                    [self.datasource addObject:model];
                }
                
            }
            
        }
        
    } else {
        
        self.datasource = [NSMutableArray array];
        
        if ([self.bodyWithTimeString isEqualToString:@"全部时间"]) {
            
            self.datasource = [NSMutableArray arrayWithArray:self.singleModelArray];
            
            self.Time = self.bodyWithTimeString;
            
        } else if ([self.bodyWithTimeString isEqualToString:@"20分钟以上"]){
            
            NSMutableString *string = [NSMutableString stringWithFormat:@"%@", self.bodyWithTimeString];
            
            self.Time = self.bodyWithTimeString;
            
            for (SingleModel *model in self.otherDataSource) {
                if (model.time >= string.intValue * 60) {
                    [self.datasource addObject:model];
                }
                
            }
            
        } else {
            
            NSMutableString *string = [NSMutableString stringWithFormat:@"%@", self.bodyWithTimeString];
            
            self.Time = self.bodyWithTimeString;
            
            for (SingleModel *model in self.otherDataSource) {
                
                if (model.time >= (string.intValue - 5) * 60 && model.time <= (string.intValue + 1) * 60) {
                    [self.datasource addObject:model];
                }
                
            }
            
        }
        
    }
    
    [self.tableView reloadData];
    
}

#pragma mark - 数据解析
- (void)getData {

    self.sendNextArray = [NSMutableArray arrayWithCapacity:0];
    self.datasource = [NSMutableArray arrayWithCapacity:0];
    [ZJPAFNetTool GETNetWithUrl:@"http://api.fit-time.cn/ftvideo/getAllVideos" body:nil headFile:nil response:ZJPJSON success:^(id result) {
        
        self.singleModelArray = [NSMutableArray arrayWithCapacity:0];
        self.bodyArray = [NSMutableArray arrayWithCapacity:0];
        for (NSDictionary *dic in result[@"videos"]) {
            self.singleModel = [[SingleModel alloc] initWithDic:dic];
            [self.singleModelArray addObject:self.singleModel];
            [self.bodyArray addObject:self.singleModel.part];
        }
        self.datasource = self.singleModelArray;
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        
    }];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end